package com.my.core.plugin;

import java.util.List;

import com.jfinal.config.Routes;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import com.my.common.BaseController;
import com.my.common.DictKeys;
import com.my.core.annotation.ControllerMapping;
import com.my.core.kit.ClassSearchKit;
import com.my.core.kit.ConfigKit;

/**
 * Routes 工具类 自动绑定Controller
 */
public class RoutesPlugin implements IPlugin{
	protected final  Log log = Log.getLog(getClass());
	
	private Routes me;
	
	public RoutesPlugin(Routes me) {
		this.me = me;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked"})
	public boolean start() {
		String scanPackage = ConfigKit.getStr(DictKeys.config_controller_scan_package, "");
		List<Class<? extends BaseController>> list = ClassSearchKit.of(BaseController.class).scanPackages(scanPackage).search();//获取所有继承BaseController
		if (list != null && list.isEmpty() == false) {
			for(Class clz : list) {
				ControllerMapping controllerMapping = (ControllerMapping) clz.getAnnotation(ControllerMapping.class);
				if(controllerMapping == null ){
					log.error(clz.getName()
							+ "继承了" + clz.getSuperclass().getSimpleName() +"，但是没有注解绑定映射路径");
					continue;
				}
				
				// 获取映射路径数组
				String controllerKey = controllerMapping.path().trim();
				String viewPath = controllerMapping.viewPath();
				boolean hasViewPath = viewPath.length() > 0;
				if (controllerKey.equals("")) {
					log.error(clz.getName() + "注解错误，映射路径为空");
					continue;
				}
					// 注册映射
					if (hasViewPath) {
						me.add(controllerKey, clz, viewPath);
					} else {
						me.add(controllerKey, clz);
					}
				}
		}
		return true;
	}


	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
}
